<?php

namespace App\Http\Controllers\Api;

use App\Models\Shop\Cart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Facades\JWTAuth;

class CartController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index()
   {
      $carts = Cart::all_carts();
      return response()->json($carts);
   }

   /**
    * Store a newly created resource in storage.
    *  加入购物车
    * @param \Illuminate\Http\Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id
      $cart = Cart::where('product_id', $request->product_id)->where('user_id', $user->id)->first();

      //判断是否有商品。有则数量加1
      if ($cart) {
         Cart::where('id', $cart->id)->increment('num');
      } else {
         Cart::create([
            'product_id' => $request->product_id,
            'user_id' => $user->id,
            'num' => 1
         ]);
      }
   }

   /**
    * 改变数量
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function change_num(Request $request)
   {
      if ($request->type == 'add') {
         Cart::where('id', $request->id)->increment('num');
      } else {
         Cart::where('id', $request->id)->decrement('num');
      }
   }


   /**
    * Remove the specified resource from storage.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      Cart::destroy($id);
   }
}
